package com.yuantu.judiciary.security.handler;

import com.yuantu.judiciary.common.Response;
import com.yuantu.judiciary.common.SysCode;
import com.yuantu.judiciary.utils.GenericJacksonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义无权访问处理类
 *
 * @author syw
 */
public class RestAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().println(GenericJacksonUtil.objectToJson(new Response(SysCode.UN_AUTHENTICATION.getCode(), SysCode.UN_AUTHENTICATION.getMessage(), accessDeniedException.getMessage())));
        response.getWriter().flush();
    }
}
